<template>
  <!-- 选择打印机 -->
  <UniPopup ref="selectPrinter" backgroundColor="#fff" :borderRadius="borderRadius" :z-index="999">
    <view class="popup-content" :style="{ borderRadius }">
      <view class="h-48 disFlxCC fz-16 popup-title">
        <text>请选择打印机</text>
      </view>
      <view class="px-16 py-10 fz-14 popup-tips">
        <text class="ali-icon">&#xe699;</text>
        <text>仅显示在线的打印机</text>
      </view>
      <scroll-view
        class="list-view"
        scroll-y
        :enable-flex="true"
        scroll-with-animation
        scroll-anchoring
        :enhanced="true"
        :show-scrollbar="false"
      >
        <Paglist
          v-model="dataList"
          :is-init-api="isInitApi"
          :parame="{
            activityId,
            size: 20,
          }"
          @register="register"
          :is-show-loadmore="false"
        >
          <template v-for="v in dataList" :key="v.id">
            <view class="list-item px-16 py-12 fz-14 disFlxJS" @click="handleItemClick(v)">
              <view>
                <text>{{ v.orgName }}</text>
                <text class="mx-4">-</text>
                <text>{{ v.printerNo }}</text>
              </view>
              <view>
                <text
                  v-if="selectedItem?.id === v.id"
                  class="ali-icon fz-20"
                  style="color: #2878ff"
                >
                  &#xe693;
                </text>
                <text v-else class="ali-icon fz-20">&#xe690;</text>
              </view>
            </view>
          </template>
        </Paglist>
        <view class="px-16 py-12 fz-12" style="color: #969799">
          <text>
            如果未找到想要的打印机，请前往PC后台【活动详情】-【签到码/胸卡打印管理】内查看打印机状态是否在线。
          </text>
        </view>
      </scroll-view>
      <view class="popup-bottom pt-12 px-24" :class="{ 'pb-12': !isNewIphone() }">
        <TButton
          :text="isPrint ? '确定打印' : '确定选择'"
          :disabled="!selectedItem"
          type="primary"
          class="gutter-btn"
          custom-class="h-44 linh-44 br-22 px-16"
          @click="handleSubmit"
        />
      </view>
    </view>
  </UniPopup>
</template>

<script setup lang="ts">
  import UniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
  import { getCurrentInstance, provide, ref } from 'vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { isNewIphone } from '@/utils/is';
  import { activityManagerDeviceActList, activityManagerPrintChestCard } from '@/api/activity';
  import Paglist from '@/components/Paglist/index.vue';
  import { useConList } from '@/components/Paglist/useConList';
  import type { ActivityManagerDeviceActListResult } from '@/api/activity/types';
  import { Toast } from '@/utils';
  import { propTypes } from '@/utils/propTypes';

  export interface SelectPrinterRef {
    show: (registerId?: number) => void
  }

  const props = defineProps({
    modelValue: propTypes.string.def(''),
    isInitApi: propTypes.bool.def(false),
    activityId: {
      type: Number,
      required: true,
    },
    isEmpty: propTypes.bool.def(false),
    isPrint: propTypes.bool.def(true),
  });

  const emits = defineEmits(['update:isEmpty', 'submit', 'update:modelValue']);
  const borderRadius = ref('32rpx 32rpx 0px 0px');

  const dataList = ref<ActivityManagerDeviceActListResult[]>([]);
  provide('api', async (obj: any) => {
    const list = await activityManagerDeviceActList(obj)
    if (list.records.length) {
      selectedItem.value = list.records[0];
      emits('update:modelValue', list.records[0]?.printerNo);
    }
    if (list.records.length === 0) {
      emits('update:isEmpty', true);
    }
    return list
  });
  const [register, { refresh }] = useConList();

  const _this = getCurrentInstance();
  const openPopup = (direction: string = 'bottom') => {
    (_this?.refs['selectPrinter'] as any).open(direction);
  };

  const closePopup = (direction: string = 'bottom') => {
    (_this?.refs['selectPrinter'] as any).close(direction);
  };

  const registerIdRef = ref<number>();

  const selectedItem = ref<ActivityManagerDeviceActListResult>();
  function handleItemClick(item: ActivityManagerDeviceActListResult) {
    selectedItem.value = item;
  }

  function handleSubmit() {
    if (!selectedItem.value) return Toast('请先选择打印机');
    if (!props.isPrint) {
      emits('submit', selectedItem.value?.printerNo);
      emits('update:modelValue', selectedItem.value?.printerNo);
      closePopup();
      return;
    }
    if (!registerIdRef.value) return Toast('报名ID不存在');
    activityManagerPrintChestCard({
      activityId: props.activityId,
      registerId: registerIdRef.value as number,
      equipmentNumber: selectedItem.value?.printerNo,
    }).then(() => {
      emits('update:modelValue', selectedItem.value?.printerNo);
      closePopup();
      Toast('打印成功');
    });
  }

  defineExpose<SelectPrinterRef>({
    show: (registerId?: number) => {
      registerIdRef.value = registerId;
      selectedItem.value = void 0
      refresh()
      openPopup();
    },
  });
</script>
<style lang="scss" scoped>
  .popup-content {
    background-color: #f2f3f5;
    overflow: hidden;
    .popup-title {
      width: 100%;
      color: #292928;
      background-color: #fff;
    }
    .popup-bottom {
      width: 100%;
      box-sizing: border-box;
      background-color: #fff;
    }
    .popup-tips {
      color: #e29942;
      background-color: #fff4e7;
    }
    .list-view {
      width: 100%;
      box-sizing: border-box;
      height: 800rpx;
      .list-item {
        color: #333;
        background-color: #fff;
      }
    }
  }
</style>
